#include "jxldecoder.h"
#include <QFile>

jxlDecoder::jxlDecoder()
{
    jxldecoder=new QProcess(this);
    connect(jxldecoder,static_cast<void(QProcess::*)(int, QProcess::ExitStatus)>(&QProcess::finished),this,&jxlDecoder::Verify);//转换后触发验证
}

bool jxlDecoder::inputTask(QStringList input, QStringList output, QStringList parameter, bool deleteSource)
{
    if(jxldecoder->state()!=0){
        return false;//有任务正在运行，拒绝任务
    }

    //初始化
    TaskList.clear();
    currentTaskNum=0;
    errTaskNum=0;

    inputList=input;
    outputList=output;
    parameterList=parameter;
    delSource=deleteSource;

    Convert();
    return true;
}

void jxlDecoder::Convert()//转换
{


    //判断队列还未完成,继续任务
    if(currentTaskNum<inputList.size()){
        //输入文件不存在,报错并开始下一个
        if(!QFile::exists(inputList.at(currentTaskNum))){
            emit convertLog("\njxlgui:"+inputList.at(currentTaskNum)+" file does not exist.\n");
            emit convertResult(currentTaskNum,0);
            currentTaskNum++;
            Convert();
            return;
        }

        QString argument='"'+inputList.at(currentTaskNum)+'"'+" "+'"'+outputList.at(currentTaskNum)
                +'"'+" "+parameterList.at(currentTaskNum);//文件名加引号，防止文件名含空格
        jxldecoder->setNativeArguments(argument);
        jxldecoder->start(djxlFilename);
        //jxlencoder->waitForFinished();
    }
    else {

    }

}

void jxlDecoder::Verify()//验证
{

    QString result=jxldecoder->readAllStandardError();//读取输出结果,实测Output无效，Error有效
    emit convertLog(result);
    //QStringList resultList = result.simplified().split(" ");//Error
    bool errorLog=result.contains("error",Qt::CaseInsensitive)||result.contains("failed",Qt::CaseInsensitive)||result.contains("couldn't",Qt::CaseInsensitive);

    if(QFile::exists(outputList.at(currentTaskNum))&&!errorLog)
    {
        if(delSource){
            if(QFile::remove(inputList.at(currentTaskNum))){
                emit convertLog("\njxlgui:"+inputList.at(currentTaskNum)+" deleted\n");
            }
            else {
                emit convertLog("\njxlgui:"+inputList.at(currentTaskNum)+" delete failed\n");
            }

        }
        emit convertResult(currentTaskNum,1);
    }
    else {
        emit convertResult(currentTaskNum,0);
    }


    currentTaskNum++;//队列序数+1

    Convert();//验证结束继续转换
}

int jxlDecoder::state()
{
    return jxldecoder->state();
}
